package com.xin.data.simbapesa.base;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

import com.google.gson.JsonObject;
import com.xin.data.simbapesa.PathMaping;
import com.xin.data.simbapesa.R;
import com.xin.data.simbapesa.SimbaApp;
import com.xin.data.simbapesa.activity.SimbaAccountActivity;
import com.xin.data.simbapesa.activity.SimbaCodeActivity;
import com.xin.data.simbapesa.activity.SimbaContactActivity;
import com.xin.data.simbapesa.activity.SimbaOcrActivity;
import com.xin.data.simbapesa.activity.SimbaPersonalActivity;
import com.xin.data.simbapesa.activity.SimbaFaceActivity;
import com.xin.data.simbapesa.analysis.AnalysisUtil;
import com.xin.data.simbapesa.api.PU;
import com.xin.data.simbapesa.api.RxHttp;
import com.xin.data.simbapesa.api.U;
import com.xin.data.simbapesa.dialog.FailedDialog;
import com.xin.data.simbapesa.dialog.LoadingDialog;
import com.xin.data.simbapesa.dialog.TipsDialog;
import com.xin.data.simbapesa.dialog.ToastDialog;
import com.xin.data.simbapesa.obj.SimbaUserProcess;
import com.xin.data.simbapesa.utils.AESCryptUtilJar;
import com.xin.data.simbapesa.utils.BarUtils;
import com.xin.data.simbapesa.utils.JsonParse;
import com.xin.data.simbapesa.utils.LogUtil;
import com.xin.data.simbapesa.utils.OrderUtils;
import com.xin.data.simbapesa.utils.PhoneUtils;
import com.xin.data.simbapesa.utils.ResUtils;
import com.xin.data.simbapesa.utils.Tools;


import java.util.HashMap;
import java.util.TimeZone;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;


public abstract class BaseActivity<VB extends ViewBinding> extends AppCompatActivity {


    protected VB binding;

    LoadingDialog mLoadingDialog;

    TipsDialog mTipsDialog;

    ToastDialog mToastDialog;

    protected String UP_TYPE1;

    protected String UP_TYPE2;


    FailedDialog failedDialog;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        if (PhoneUtils.isFayu(getActivity())) {
            Tools.selectLanguage(this, "fr");
        } else {
            String tz = TimeZone.getDefault().getID();
            if (tz.equals("Africa/Douala")) {
                Tools.selectLanguage(this, "fr");
            } else {
                Tools.selectLanguage(this, "en");
            }
        }

        super.onCreate(savedInstanceState);
        SimbaApp.getInstance().addActivity(this);

        SimbaApp.getInstance().setContext(this);

        init();
        binding = initViewBinding(getLayoutInflater());
        setContentView(binding.getRoot());
        setStatusBarHeight(binding.getRoot());
        initView();
        initData();

    }


    protected abstract VB initViewBinding(LayoutInflater inflater);

    protected abstract void initView();

    protected abstract void initData();

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(UP_TYPE1)) {
            PU.userBuriedPoint(UP_TYPE1, "");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (!TextUtils.isEmpty(UP_TYPE2)) {
            PU.userBuriedPoint(UP_TYPE2, "");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
            mLoadingDialog.colse();
        }
        if (mTipsDialog != null) {
            mTipsDialog.dismiss();
            mTipsDialog.colse();
        }
        if (failedDialog != null) {
            failedDialog.dismiss();
            failedDialog.colse();
        }
    }

    public void showFailedDialog(BaseDialog.BtnClickListener onBtnClickListener) {
        if (binding != null && !isFinishing() && !isDestroyed()) {
            if (failedDialog == null) {
                failedDialog = new FailedDialog(getActivity());
            }
            failedDialog.setActivity(getActivity());
            failedDialog.setOnBtnClickListener(onBtnClickListener);
            failedDialog.show();
        }
    }


    void init() {
        Window window = getWindow();

        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);

        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

        window.setStatusBarColor(Color.TRANSPARENT);
        BarUtils.setNavigationBar(this, false);

        BarUtils.showLightStatusBars(this, true);
    }

    public void setStatusBarHeight(View view) {
        int h = BarUtils.getStatusBarHeight(this);
        if (h <= 0) {
            h = BarUtils.getStatusBarHeightByReflection(this);
        }
        if (h <= 0) {
            h = BarUtils.getStatusBarHeightViaInsets(this);
        }
        if (view == null) {
            binding.getRoot().setPadding(0, 0, 0, 0);
        } else {
            view.setPadding(0, h, 0, 0);
        }
    }

    public void setStatusBarHeight1(View view, int b) {
        int h = BarUtils.getStatusBarHeight(this);
        if (h <= 0) {
            h = BarUtils.getStatusBarHeightByReflection(this);
        }
        if (h <= 0) {
            h = BarUtils.getStatusBarHeightViaInsets(this);
        }
        if (view == null) {
            binding.getRoot().setPadding(0, 0, 0, 0);
        } else {
            view.setPadding(0, h, 0, b);
        }
    }

    public void setStatusBarHeight2(View view, int left, int right, int bottom) {
        int h = BarUtils.getStatusBarHeight(this);
        if (h <= 0) {
            h = BarUtils.getStatusBarHeightByReflection(this);
        }
        if (h <= 0) {
            h = BarUtils.getStatusBarHeightViaInsets(this);
        }
        if (view == null) {
            binding.getRoot().setPadding(0, 0, 0, 0);
        } else {
            view.setPadding(left, h, right, bottom);
        }
    }

    public void setStatusBarColor() {
        BarUtils.showLightStatusBars(this, true);
        BarUtils.setStatusBarColor(this, Color.WHITE);
    }


    public void showLoading(String title) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(this);
        }
        if (!isFinishing()) {
            if (!TextUtils.isEmpty(title)) {
                mLoadingDialog.setTitle(title);
            } else {
                mLoadingDialog.setTitle(ResUtils.s(R.string.loading));
            }
            mLoadingDialog.show();
        }
    }

    public void hideLoading() {
        if (mLoadingDialog != null && !isFinishing()) {
            mLoadingDialog.dismiss();
        }
    }

    public void showTipsDialog(String title, String cancelTxt, String okTxt, String content, boolean isHide, BaseDialog.BtnClickListener onBtnClickListener) {
        if (mTipsDialog == null) {
            mTipsDialog = new TipsDialog(this);
        }
        if (!TextUtils.isEmpty(title)) {
            mTipsDialog.setTitle(title);
        } else {
            mTipsDialog.setTitle(ResUtils.s(R.string.tips_title));
        }
        if (!TextUtils.isEmpty(cancelTxt)) {
            mTipsDialog.setCancelTxt(cancelTxt);
        } else {
            mTipsDialog.setCancelTxt(ResUtils.s(R.string.tips_btn1));
        }
        if (!TextUtils.isEmpty(okTxt)) {
            mTipsDialog.setOkTxt(okTxt);
        } else {
            mTipsDialog.setOkTxt(ResUtils.s(R.string.tips_btn2));
        }

        mTipsDialog.setContentTxt(content);

        mTipsDialog.hideCancel(isHide);

        if (onBtnClickListener != null) {
            mTipsDialog.setOnBtnClickListener(onBtnClickListener);
        }

        if (!isFinishing()) {
            mTipsDialog.show();
        }

    }

    public void hideTipsDialog() {
        if (mTipsDialog != null) {
            mTipsDialog.dismiss();
        }
    }

    public void showToastDialog(int icon, String txt) {
        if (mToastDialog == null) {
            mToastDialog = new ToastDialog(this);
        }
        mToastDialog.setIcon(icon);
        mToastDialog.setTitle(txt);
        if (!isFinishing()) {
            mToastDialog.show();
        }
    }

    public void userProcess(UserProcessInterface onUserProcessInterface, boolean isLoading) {

        if (isLoading) {
            showLoading(ResUtils.s(R.string.loading));
        }
        String channelCode = AnalysisUtil.INSTANCE.channelCode();
        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[8]);
        json.addProperty("mobile", U.URL_PHONE);
        json.addProperty("userId", U.URL_USERID);
        json.addProperty("channelCode", channelCode);
        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }
        String data = AESCryptUtilJar.encryptDefault(json.toString());
        LogUtil.e("me", json + "<-userProcess post->" + data);
        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        if (binding != null) {
                            if (isLoading) {
                                hideLoading();
                            }
                            if (!TextUtils.isEmpty(s)) {
                                String json1 = AESCryptUtilJar.decryptDefault(s);
                                LogUtil.e("me", "userProcess json->" + json1);
                                if (JsonParse.getCode(json1)) {
                                    JsonParse.userProcessJson2Obj(json1);
                                }
                            }
                            if (onUserProcessInterface != null) {
                                onUserProcessInterface.onRequestResult();
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if (binding != null && isLoading) {
                            hideLoading();
                            if (onUserProcessInterface != null) {
                                onUserProcessInterface.onRequestResult();
                            }
                            LogUtil.e("me", "userProcess e->" + e);
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    public void userProcess(String token, UserProcessInterface onUserProcessInterface, boolean isLoading) {

        if (isLoading) {
            showLoading(ResUtils.s(R.string.loading));
        }
        String channelCode = AnalysisUtil.INSTANCE.channelCode();
        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[8], U.URL_PRODUCT, token);
        json.addProperty("mobile", U.URL_PHONE);
        json.addProperty("userId", U.URL_USERID);
        json.addProperty("channelCode", channelCode);
        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_PRODUCT);
        }
        String data = AESCryptUtilJar.encryptDefault(json.toString());
        LogUtil.e("me", json + "<-userProcess post->" + data);
        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        if (binding != null) {
                            if (isLoading) {
                                hideLoading();
                            }
                            if (!TextUtils.isEmpty(s)) {
                                String json1 = AESCryptUtilJar.decryptDefault(s);
                                LogUtil.e("me", "userProcess json->" + json1);
                                if (JsonParse.getCode(json1)) {
                                    JsonParse.userProcessJson2Obj(json1);
                                }
                            }
                            if (onUserProcessInterface != null) {
                                onUserProcessInterface.onRequestResult();
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if (binding != null) {
                            if (isLoading) {
                                hideLoading();
                            }
                            if (onUserProcessInterface != null) {
                                onUserProcessInterface.onRequestResult();
                            }
                            LogUtil.e("me", "userProcess e->" + e);
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    public void showSMSDialog(int type, String mobileEditFlag, String phoneTxt, Activity activity, boolean isTelegram) {
        String content;
        if (type == 1) {
            content = ResUtils.s(R.string.code_subtitle1);
        } else {
            content = ResUtils.s(R.string.code_subtitle2);
        }
        showTipsDialog(ResUtils.s(R.string.tips_title), "", "", content, true, new BaseDialog.BtnClickListener() {
            @Override
            public void btnOnClickOk() {
                toCheckCode(mobileEditFlag, phoneTxt, isTelegram);
                if (activity != null) {
                    activity.finish();
                }
            }

            @Override
            public void btnOnClickCancel() {
                toCheckCode(mobileEditFlag, phoneTxt, isTelegram);
                if (activity != null) {
                    activity.finish();
                }
            }

            @Override
            public void btnOnClickColse() {
                toCheckCode(mobileEditFlag, phoneTxt, isTelegram);
                if (activity != null) {
                    activity.finish();
                }
            }
        });
    }

    void toCheckCode(String mobileEditFlag, String phoneTxt, boolean isTelegram) {
        LogUtil.e("me", "mobileEditFlag->" + mobileEditFlag);
        Intent intent = new Intent(getActivity(), SimbaCodeActivity.class);
        intent.putExtra("phoneNumber", phoneTxt);
        intent.putExtra("mobileEditFlag", mobileEditFlag);
        intent.putExtra("isTelegram", isTelegram);
        startActivity(intent);
    }

    public void checkCode() {
        SimbaUserProcess process = SimbaApp.getInstance().getProcess();
        if (process != null) {
            if ((!TextUtils.isEmpty(process.getWhatsappFlag()) && process.getWhatsappFlag().equals("YES")) || (!TextUtils.isEmpty(process.getSmsFlag()) && process.getSmsFlag().equals("YES")) || (!TextUtils.isEmpty(process.getTelegramFlag()) && process.getTelegramFlag().equals("YES"))) {
                int state = OrderUtils.getOrderStatus();
                boolean isTelegram = !TextUtils.isEmpty(process.getTelegramFlag()) && process.getTelegramFlag().equals("YES");
                if (state <= 0) {
                    showSMSDialog(1, process.getMobileEditFlag(), U.URL_PHONE, null, isTelegram);
                } else {
                    showSMSDialog(2, process.getMobileEditFlag(), U.URL_PHONE, null, isTelegram);
                }
            }
        }
    }

    public boolean checkSteps(Activity... activitys) {
//        startActivity(new Intent(this, SimbaScoreActivity.class));
//        return true;
        SimbaUserProcess process = SimbaApp.getInstance().getProcess();
        if (process != null) {
            if (process.getWhatsappFlag().equals("YES") || process.getSmsFlag().equals("YES")) {
                int state = OrderUtils.getOrderStatus();
                Activity activity = null;
                if (activitys != null && activitys.length > 0) {
                    activity = activitys[0];
                }
                boolean isTelegram = !TextUtils.isEmpty(process.getTelegramFlag()) && process.getTelegramFlag().equals("YES");
                if (state <= 0) {
                    showSMSDialog(1, process.getMobileEditFlag(), U.URL_PHONE, activity, isTelegram);
                } else {
                    showSMSDialog(2, process.getMobileEditFlag(), U.URL_PHONE, activity, isTelegram);
                }
                return true;
            } else if (process.getSteps() != null && process.getSteps().length > 0) {
                String step = process.getSteps()[0];
                LogUtil.e("me", "checkSteps step->" + step);
                switch (step) {
                    case "personal_info": {
                        Intent intent = new Intent(this, SimbaPersonalActivity.class);
                        intent.putExtra("type", 1);
                        startActivity(new Intent(intent));
                        return true;
                    }
                    case "work_info": {
                        Intent intent = new Intent(this, SimbaPersonalActivity.class);
                        intent.putExtra("type", 2);
                        startActivity(new Intent(intent));
                        return true;
                    }
                    case "contact_info":
                        startActivity(new Intent(this, SimbaContactActivity.class));
                        return true;
                    case "account_info":
                        if (process.getAccount_info() != null) {
                            Intent intent = new Intent(this, SimbaPersonalActivity.class);
                            intent.putExtra("type", 3);
                            startActivity(new Intent(intent));
                        } else {
                            startActivity(new Intent(this, SimbaAccountActivity.class));
                        }
                        return true;
                    case "ocr_info":
                        startActivity(new Intent(this, SimbaOcrActivity.class));
                        return true;
                    case "sefie_info":
                        startActivity(new Intent(this, SimbaFaceActivity.class));
                        return true;
                }
            }
        }
        return false;
    }


    public AppCompatActivity getActivity() {
        return this;
    }


    public interface UserProcessInterface {
        void onRequestResult();
    }

}
